<template>

  <van-nav-bar
      title="发布帖子"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
  />



  <van-form @submit="onS">

    <van-field name="radio" label="活动主题">
      <template #input>
        <van-radio-group v-model="typeId" direction="horizontal">
          <van-radio name="1">21天攒图计划招募令</van-radio>
          <van-radio name="2">快题竞赛</van-radio>
        </van-radio-group>
      </template>
    </van-field>

    <!-- 新增文本框用于输入文章内容 -->
    <van-field
        v-model="content"
        label="内容"
        type="textarea"
        rows="5"
        autosize
        placeholder="请输入文章内容"
        required
    />
    <div class="image-upload">
      <van-uploader
          :after-read="handleRead"
          :max-size="5 * 1024 * 1024"
          :upload-text="'点击上传'"
      />

    </div>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        发布
      </van-button>
    </div>


    <!-- 添加发帖规范提示及跳转链接 -->
    <div style="text-align: center; margin-top: 8px;">
      <van-button size="small" type="default" @click="toPostingGuidelines">
        发帖规范
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import {ref} from "vue";
import {showToast} from 'vant';
import {useRouter} from "vue-router";
import {post} from "../../util/request";
import {postFile} from "../../util/reqeustfile"; // 确保正确导入 Toast


const router = useRouter();
const typeId = ref('0');
const content = ref('');
const urlList = ref([]);


const onClickLeft = () => history.back();
const onS = () => {
  if (!content.value.trim()) {
    showToast('内容不能为空'); // 使用Toast提示用户
    return; // 阻止后续操作
  };


  // 发送请求到后端接口
  post('circle/addCircleArticle', {
    typeId: typeId.value,
    content: content.value,
    urlList: urlList.value
  })
      .then(response => {
        if (response.data.code == 0) {
          console.log('Article created successfully');
          // 这里可以根据需要处理成功的逻辑，比如显示提示信息
          //清空数据
          typeId.value = '0';
          content.value = '';
          urlList.value = [];
        } else {
        }
      }, error => {
        console.error('Error creating article:', error);
        // 处理错误逻辑
      });
}
const handleRead =( async (file) =>{
  // console.log(file)
  // console.log(file.file)
  // const formData = new FormData();
  // formData.append('file', file.file); // 确保file.file是正确的，如果file就是文件对象，则应该是formData.append('file', file);

  // 发送POST请求到您的后端接口，确保传递formData且不包含多余的headers配置
  const response = await postFile('study/article/upload', file);
  urlList.value.push(response.data.data);
  console.log(urlList.value);
  // 这里可以根据需要处理成功的逻辑，比如显示提示信息
});

const toPostingGuidelines = () => {
  router.push('/message');
};

</script>

<style scoped>
.image-upload {
  /* Your custom styles */
}
</style>